package com.javacoo.swing.jxbrowser.engine;

import java.awt.BorderLayout;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.ProductInfo;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * 获取帧ID
 * <li></li>
 * JxBrowser API提供的功能允许在加载的网页上获取帧ID层次结构
 * @author: duanyong@jccfc.com
 * @since: 2020/9/24 9:00
 */
public class GettingFrameIDs extends BaseBrowser {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    printFramesHierarchy(event.getBrowser(), Browser.MAIN_FRAME_ID);
                }
            }
        });
        browser.loadURL("http://docs.oracle.com/javase/8/docs/api/");
        //获取产品版本
        System.out.println("JxBrowser version: " + ProductInfo.getVersion());
    }
    public static void printFramesHierarchy(Browser browser, long parentFrameId) {
        List<Long> childFrameIds = browser.getFramesIds(parentFrameId);
        for (Long childFrameId : childFrameIds) {
            System.out.println("Child Frame: " + childFrameId +
                ", HTML: " + browser.getHTML(childFrameId));
            printFramesHierarchy(browser, childFrameId);
        }
    }
}
